import { ScorePanel } from "./scorePanel"
import { Snake } from "./snake"
import { Food } from "./food"

const KEY_VALUE: Array<string> = ["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"];

export class GameControl {
	scorePanel: ScorePanel;
	food: Food;
	snake: Snake;
	direction: string = "ArrowRight";
	isLeve: boolean = false;
	constructor() {
		this.food = new Food;
		this.scorePanel = new ScorePanel(10, 1);
		this.snake = new Snake;
		this.init()
	}
	init() {
		document.addEventListener("keydown", this.handler.bind(this));
	}
	startAndStop() {
		this.isLeve = !this.isLeve;
		if (this.isLeve) {
			this.run()
		}
	}
	handler(e: KeyboardEvent) {
		console.log(this)
		if (e.code == 'Space') {
			this.startAndStop()
			return
		}

		if (KEY_VALUE.includes(e.key)){
			if (this.isLeve && e.key) {
				this.direction = e.key;
			}
		}
	}
	run() {
		let { X, Y } = this.snake;
		switch (this.direction) {
			case "ArrowUp":
			case "Up":
				Y -= 10;
				break;
			case "ArrowDown":
			case "Down":
				Y += 10;
				break;
			case "ArrowLeft":
			case "Left":
				X -= 10
				break;
			case "ArrowRight":
			case "Right":
				X += 10
				break;
		}
		try {
			this.snake.X = X;
			this.snake.Y = Y;
		} catch (error) {
			this.isLeve = false;
			alert(error)
		}

		if (this.checkCat(X, Y)) {
			this.food.change()
			this.snake.addBody(X, Y)
			this.scorePanel.addScore()
		}
		this.isLeve && setTimeout(() => {
			this.run()
		}, 300 - (this.scorePanel.level - 1) * 25)
	}

	checkCat(X: number, Y: number): boolean {
		if (X == this.food.X && Y == this.food.Y) {
			return true
		} else {
			return false
		}
	}
}

export default GameControl